<template>
  <div>
    <el-button v-show="candownload" @click="downloadDocx">下载文档</el-button>
    <div class="markdown-body" v-html="compiledContent"></div>
  </div>
</template>

<script lang="ts">
import { Component, Vue, Prop } from 'vue-property-decorator';
import MarkdownIt from 'markdown-it';
import hljs from 'highlight.js';
import DOMPurify from 'dompurify';
import { Document, Paragraph, TextRun, Packer, BorderStyle } from "docx";
import { saveAs } from 'file-saver';

@Component
export default class MarkdownRenderer extends Vue {
  @Prop({ type: String, required: true }) readonly content!: string;
  @Prop() readonly download;
  private md = new MarkdownIt({
    html: true,
    linkify: true,
    highlight: (code, lang) => {
      if (lang && hljs.getLanguage(lang)) {
        try {
          return hljs.highlight(code, { language: lang }).value;
        } catch (__) { console.log(__) }
      }
      return code;
    }
  });

  get candownload() {
    return this.download && this.content;
  }

  get compiledContent(): string {
    const rawHtml = this.md.render(this.content);
    return DOMPurify.sanitize(rawHtml);
  }

  async downloadDocx() {
    console.log(this.content)

    const getFileName = () => {
      const firstLine = this.content.split('\n')[0] || 'document'; // 安全处理空内容
      // 清除标题标记和首尾空格（匹配 # 和空格）
      const cleanName = firstLine.replace(/^#+\s*/, '').trim();
      // 过滤非法文件名字符
      return `${cleanName.replace(/[\\/:*?"<>|]/g, '')}.docx`;
    };
    const parseFormattedText = (text: string): TextRun[] => {
      const boldRegex = /\*\*(.+?)\*\*/g; // 非贪婪匹配双星号
      const segments = text.split(boldRegex);

      return segments.map((segment, index) => {
        // 奇数索引是被捕获的加粗内容
        return index % 2 === 1
          ? new TextRun({ text: segment, bold: true })
          : new TextRun(segment);
      }).filter((run: any) => run.text !== ""); // 过滤空文本
    };

    // 改进后的段落解析逻辑
    const paragraphs = this.content.split("\n").map(line => {

      if (/^---+$/.test(line.trim())) {
          return new Paragraph({
            border: {
              bottom: {
                color: "auto",    // 自动颜色（通常黑色）
                space: 6,         // 间距（单位：磅）
                style: BorderStyle.SINGLE,  // 单线样式
                size: 2          // 线宽（单位：磅）
              }
            }
          });
        }
      // 标题解析（保留原有逻辑）
      const headingMatch = line.match(/^(#{1,6})\s*(.*)/);
      if (headingMatch) {
        const level = Math.min(headingMatch[1].length, 6);
        return new Paragraph({
          heading: `Heading${level}` as any,
          children: parseFormattedText(headingMatch[2]) // 处理标题中的加粗
        });
      }

      // 列表项解析（保留原有逻辑）
      const listMatch = line.match(/^\s*([-*+])\s+(.*)/);
      if (listMatch) {
        return new Paragraph({
          bullet: { level: 0 },
          children: parseFormattedText(listMatch[2]) // 处理列表项中的加粗
        });
      }
      // 普通段落处理（新增格式解析）
      return new Paragraph({
        children: parseFormattedText(line) // 核心处理逻辑
      });
    });

    // 创建带样式的文档
    const doc = new Document({
      styles: {
        paragraphStyles: [
          {
            id: "Heading1",
            name: "Heading 1",
            basedOn: "Normal",
            next: "Normal",
            quickFormat: true,
            run: {
              size: 24,
              bold: true,
              color: "000000"
            }
          },
          // 可添加更多样式...
        ]
      },
      sections: [{
        properties: {},
        children: paragraphs
      }]
    });

    // 生成并下载
    const blob = await Packer.toBlob(doc);
    saveAs(blob, getFileName());
  }
}
</script>
<style>
.markdown-container {
  position: relative;
}
::v-deep .markdown-body {
  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Helvetica, Arial, sans-serif;
  line-height: 1;
}
::v-deep code {
  font-family: SFMono-Regular,Consolas,Liberation Mono,Menlo,monospace;
  padding: 5px;
  background-color: rgba(175,184,193,0.2);
  border-radius: 6px;
}
body{
  margin: 0px !important;
}
</style>